var config = SMT.xconfig;
SMT.xconfig.gvar = {};
SMT.xconfig.gvar.pageNum = '1';

// ajax session过期跳转
//jQuery(function($){  
//    // 备份jquery的ajax方法    
//    var _ajax=$.ajax;  
//    // 重写ajax方法，先判断登录在执行success函数   
//    $.ajax=function(opt){  
//        var _success = opt && opt.success || function(a, b){};  
//        var _opt = $.extend(opt, {  
//            success:function(data, textStatus){  
//                // 如果后台将请求重定向到了登录页，则data里面存放的就是登录页的源码，这里需要找到data是登录页的证据(标记)  
//                if(data.indexOf('someMark') != -1) {  
//                    window.location.href= global.contextPath + "/login";  
//                    return;  
//                }  
//                _success(data, textStatus);    
//            }    
//        });  
//        _ajax(_opt);  
//    };  
//});   

var XF = window.XF = function() {
    if (typeof XF == 'undefined') 
        return window;
    else 
        return XF;
};
var _XF_NAV  = function(){
    if (typeof _XF_NAV == 'undefined') 
        return window;
    else 
        return _XF_NAV;
}

var _XF_LAYOUT = function(){
	if(typeof _XF_LAYOUT == 'undefined')
		return window;
	else
		return _XF_LAYOUT;
}

XF = new function(){
    /**
     * 富文本
     */
    this.createKindEditor = function(id){
    	var keditor = KindEditor.create('#'+id, {
			allowFileManager : true,
			fileManagerJson:global.contextPath+'/upload4KindEditor',
			uploadJson:global.contextPath+'/upload4KindEditor', 
			resizeType:1,
			items : [
			 		'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
			 		'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
			 		'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
			 		'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
			 		'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
			 		'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
			 		'insertfile','|', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
			 		'anchor', 'link', 'unlink'
			 	]
		});
    	window.keditor = keditor ;
    };
    
    this.dateFormatter = function(date){
    	var y = date.getFullYear();
    	var m = date.getMonth()+1;
    	var d = date.getDate();
    	return y + "-" + m + "-" + d;
    };
    
    this.dateParse = function(s){
    	if(""==s){
    		return null;
    	}
    	var t = Date.parse(s);
    	if (!isNaN(t)){
    		return new Date(t);
    	} else {
			var arr = s.split("-");
			s = arr[2]+"/" + arr[1] + "/" + arr[0];
			var tt = new Date();
			tt.setFullYear(arr[0]);
			tt.setMonth(parseInt(arr[1])-1);
			tt.setDate(arr[2]);
			if(tt instanceof Date){
				return tt;
			}else {
				return new Date();
			}
		} 
    }
    
    this.uploadFile = function(id,sid){
		$("#"+id).uploadify({
	        auto: true,
	        multi:false,
	        uploader: global.contextPath + "/servlet/upload?jsessionid="+sid,
	        swf: global.contextPath + '/js/jplugin/uploadify/uploadify.swf',
	        onUploadSuccess:function(file, data, response){
	        	var fileName = file.name;
	        	var data = JSON.parse(data);
	        	if(data['status']=='0'){
	        		$("#uploadResultLabel").html(fileName);
	        		$("input[name=tempFileId]").val(data['fileId']);
	        		var nameEle = $("input[name=name]");
	        		if(nameEle.val()==""){
	        			nameEle.val(fileName);
	        		}
	        	}else if(data['status']=='1'){
	        		var s = "上传失败："+data['errorMessage'];
	        		$("#uploadResultLabel").html("<span style='color:#ff0000'>"+s+"</span>");
	        	}
	        }
	    });
    };
    
    /**
     * 高亮侧边链接
     */
    this.lightSideBar = function(linkName){
    	$("#sidebar li a").removeClass("light");
    	$("#sidebar li a[s="+linkName+"]").addClass("light");
    };
    
    this.loadMap = function(){
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://api.map.baidu.com/api?v=2.0&ak=BhnIKXHC4luCst3qvbTGrPOD&callback=initBaiduMap";
		document.body.appendChild(script);
    }
    
    this.localCoordinate = function(){
    	var v = $("input[name=addressText]").val();
    	if(typeof(BMap)!='undefined' && typeof(window.BaiduMap)!='undefined'){
        	var myGeo = new BMap.Geocoder();
        	myGeo.getPoint(v, function(point){
        		if (point) {
        			var map = window.BaiduMap;
        			map.centerAndZoom(point, 16);
        			map.clearOverlays(); 
        			map.addOverlay(new BMap.Marker(point));
        			var x = point.lng;
        			var y = point.lat;
        			$("input[name=coordinate]").val(x+","+y);
        		}else{
        			alert("您选择地址没有解析到结果!");
        		}
        	});
    	}
    }
    
	
	this.refreshAfterAddFaild = function(errorJson){
		if(typeof(errorJson)=="undefined")return;
		if(errorJson==null || errorJson=="")return;
		$("span[id*='errorTip']").hide();
		for(key in errorJson){
			var v = errorJson[key];
			var errorTip = $("#errorTip_"+key);
			errorTip.html(v);
			errorTip.show();
		}
	};
	
	this.hideError = function() {
		$("span[id*='errorTip']").hide();
	};
    
}();

//打印脚本
function onClickPrint(){
	var div, prinPannel = "AutoPrintPannel";
	if(!document.getElementById(prinPannel)){
		div = document.createElement('div')
		div.id = prinPannel;
		div.className = 'toPrint';
		document.body.appendChild(div);
	}else{
		div = document.getElementById(prinPannel);
	}
	$(div).append(document.getElementById("printPannel").innerHTML);
	$(".panel").addClass("noPrint"); 
	window.focus();
	if (!!window.ActiveXObject || "ActiveXObject" in window) {
		document.body.className += ' ext-ie';
		document.execCommand('print', false, null);
	} else {
		window.print();
	}
	$(div).html('');
}

function pageNumInput(href){ 
    var pageNumInput = $('#pageNumInput'); 
    if(!checkPageNumInput(pageNumInput)){ 
        pageNumInput.val(''); 
        pageNumInput.focus(); 
        return false; 
    } 
    SMT.jumpPage(pageNumInput.val(), href);
}
function checkPageNumInput(obj){
	var pageCount = $('#pageNumInput').attr("count");
	pageCount = parseInt(pageCount);
    if(obj.val()=="" || isNaN(obj.val())){ 
        alert('请输入数字！'); 
        return false; 
    }else if(obj.val()<1 || obj.val()>pageCount){ 
        alert('请输入正确的页数！'); 
        return false; 
    }else{ 
        return true; 
    } 
}


_XF_NAV = new function(){
	this.navTo = function(path){
		var url = global.contextPath + path;
		$.ajax({
			type:"post",
			url:url,
			complete:function(xhr){
				if (xhr.status == 200) {
					xhr = xhr['responseText'];
					$("#center").html(xhr);
				}
			}
		});
	};
	
	/**
	 * 选中主菜单
	 */
	this.activeTab = function(tab){
		$(".navbar a").removeClass("active");
		$(".navbar a[s="+tab+"]").addClass("active");
	};
    /**
	 * iframe支持
     * @param url
     * @constructor
     */
    this.Open = function(url){
        $("#center").html('<iframe name="mainframe" frameborder="0" src="'+url+'" style="height:100%;width:100%;"></iframe>');
    };

}();

_XF_LAYOUT = new function(){
	this.resizeWest = function(){
		$('#sidebar').accordion({
	        animate:true
	    });
	}
}();

XF.NAV = _XF_NAV;
XF.LAYOUT = _XF_LAYOUT;

/*$.fn.winMenu = function(options) {
	var defaults = {
        'item': '.list a',
		'width' : 77,
		'nav' : '.hidnav',
		'navpannel' : '.item',
		'timeout' : 800
    };
    var settings = $.extend({}, defaults, options);
	var init = function(obj){
		var html = '',
			width = 0,
			$item = obj.find(settings.item),
			$nav = obj.find(settings.nav),
			itemCount = obj.find(settings.item).length,
			itemWith = itemCount*settings.width;
			
		upPanel();
		$(window).resize(function() {
			setTimeout(upPanel(), settings.timeout);
		});
		
		$nav.mouseover(function(){
			$(this).find(defaults.navpannel).show();
		}).mouseout(function(){
			$(this).find(defaults.navpannel).hide();
		});
		
		function upPanel(){
			width = obj.width();
			if(width<(itemWith+10)){
				var html='',
					showlen = parseInt((width-10)/settings.width);
				//隐藏所有溢出菜单
				$item.each(function(index){
					//console.log(index)
					if(index<showlen){
						$(this).show();
					}else{
						html += $(this).prop("outerHTML");
						$(this).hide();
					}
				});
				$nav.show().find(settings.navpannel).html(html).find('a').show();
			}else{
				//显示所有菜单
				obj.find(settings.item+':hidden').show();
				// 隐藏下拉菜单
				if(!$nav.is(":hidden")){
					$nav.hide().find(settings.navpannel).empty();
				}
			}
		}
	}
	return $(this).each(function() {
		init($(this));						 
	});
}*/
$.fn.winMenu = function(options) {
    var defaults = {
        'item': '.list a',
        'hd': '.header',
        'nav': '.hidnav',
        'subMenu' : '.winMenuPopup'
    };
    var Opt = $.extend({}, defaults, options);
    var init = function(obj){
        var html = '',
            itemCount = obj.find(Opt.item).length,
            barWidth = 0,
            itemWidth = 20,
            logoWidth = $(Opt.hd).find('.brand').outerWidth(true),
            infoWidth = $(Opt.hd).find('.usersNav').outerWidth(true);
        //获取总宽度
        obj.find(Opt.item).each(function(){
            itemWidth += $(this).width();
        });
        //初始化控件
        if($(Opt.subMenu).length==0){
            $('<div><div class="box"></div></div>').addClass(Opt.subMenu.replace('.','')).css({
                'position':'absolute',
                'z-index':'99999',
                'display':'none'
            }).appendTo('body');
        }
        //窗口发生变化
        setSize();
        $(window).resize(function(){
            $(Opt.subMenu).hide(); //隐藏下拉框
            setTimeout(function(){
                setSize();
            }, 100);
        });
        obj.find(Opt.nav).click(function(e){
            e.stopPropagation();
            if($(Opt.subMenu).is(":hidden")){
                $(Opt.subMenu).css({
                    'left':$(this).offset().left,
                    'top':$(this).offset().top+63
                }).show();
            }else{
                $(Opt.subMenu).hide();
            }
        });
        //绑定页面点击事件
        $(document).click(function(e) {
            if(!$(Opt.subMenu).is(":hidden")){
                $(Opt.subMenu).hide(); //隐藏下拉框
            }
        });
        function setSize(){
            var width = 0,
                curWidth = 0;

            console.log($(Opt.hd).outerWidth(true));
            console.log(logoWidth);
            console.log(infoWidth);

            barWidth = $(Opt.hd).outerWidth(true)-logoWidth-infoWidth;
            obj.width(barWidth);

            console.log(barWidth+'/'+itemWidth);

            if(itemWidth > barWidth){
                html = '';
                curWidth = itemWidth;
                obj.find(Opt.nav).show();
                for(var i=itemCount-1;  i>=0; i--){
                    html = obj.find(Opt.item).eq(i).prop("outerHTML") + html;
                    //隐藏当前控件
                    obj.find(Opt.item).eq(i).hide();
                    curWidth -= obj.find(Opt.item).eq(i).width();
                    if((curWidth-width)<barWidth){
                        while (--i>=0)
                        {
                            obj.find(Opt.item).eq(i).show();
                        }
                        $(Opt.subMenu).find('.box').html(html);
                        break;
                    }
                }
            }else{
                obj.find(Opt.item).show();
                obj.find(Opt.nav).hide();
            }
        }
    }
    return $(this).each(function() {
        init($(this));
    });
}
